package com.xht.service.impl;

import cn.hutool.json.JSONUtil;
import com.xht.constants.SystemConstants;
import com.xht.domain.ResponseResult;
import com.xht.domain.entity.LoginUser;
import com.xht.domain.entity.User;
import com.xht.service.LoginService;
import com.xht.utils.JwtUtil;
import com.xht.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static cn.hutool.core.lang.Console.log;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult login(User user) {
        /**
         * 没认证情况下第一个参数传用户名，第二个参数传用户密码
         */
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());

        /**
         * 其中执行下面方法时候，就会自动去调用UserDetailsService类中的方法
         * 然后去验证 账户密码的正确性，
         * 需要自定义UserDetailsService的实现类,
         */
        //实现用户的登录认证
        Authentication authenticate =
                //authenticate()方法会调用UserDetailsService的实现类中的loadUserByUsername方法
                // ,从中去验证用户信息是否输入正确
                authenticationManager.authenticate(authenticationToken);

        //判断是否认证通过
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户密码错误拉!!!");
        }
        //获取userId 生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //Long userId = loginUser.getUser().getId();
        User user1 = loginUser.getUser();
        Long id = user1.getId();
        //将userId进行加密,利用jwt
        // ,但是jwt需要传入一个String类型
        String jwt = JwtUtil.createJWT(id.toString());
        log(jwt);

//        //把用户信息存入redis
        stringRedisTemplate.opsForValue().set(SystemConstants.ADMIN_LOGIN + id, JSONUtil.toJsonStr(loginUser));

        //把token 返回
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return ResponseResult.okResult(map);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @Override
    public ResponseResult logout() {
        //获取redis中当前登录的用户id,并且删除redis的数据
        Long userId = SecurityUtils.getUserId();
        stringRedisTemplate.delete(SystemConstants.ADMIN_LOGIN + userId);
        return ResponseResult.okResult();
    }
}
